#!python3.2
#-*- coding: utf-8 -*-
"""gtrans.py - translate phrases using the Google Translate service

Based on gtranslate.py written by Vadym Zakovinko and modified to
work with Python 3.2
"""
import urllib.parse
import urllib.request
import urllib.error
import json

api_translate_url = 'https://www.googleapis.com/language/translate/v2'
app_id = ''

LANGUAGES = {
    'Afrikaans': 'af',
    'Albanian': 'sq',
    'Arabic': 'ar',
    'Belarusian': 'be',
    'Bulgarian': 'bg',
    'Catalan': 'ca',
    'Chinese Simplified': 'zh-CN',
    'Chinese Traditional': 'zh-TW',
    'Croatian': 'hr',
    'Czech': 'cs',
    'Danish': 'da',
    'Dutch': 'nl',
    'English': 'en',
    'Estonian': 'et',
    'Filipino': 'tl',
    'Finnish': 'fi',
    'French': 'fr',
    'Galician': 'gl',
    'German': 'de',
    'Greek': 'el',
    'Haitian Creole': 'ht',
    'Hebrew': 'iw',
    'Hindi': 'hi',
    'Hungarian': 'hu',
    'Icelandic': 'is',
    'Indonesian': 'id',
    'Irish': 'ga',
    'Italian': 'it',
    'Japanese': 'ja',
    'Latvian': 'lv',
    'Lithuanian': 'lt',
    'Macedonian': 'mk',
    'Malay': 'ms',
    'Maltese': 'mt',
    'Norwegian': 'no',
    'Persian': 'fa',
    'Polish': 'pl',
    'Portuguese': 'pt',
    'Romanian': 'ro',
    'Russian': 'ru',
    'Serbian': 'sr',
    'Slovak': 'sk',
    'Slovenian': 'sl',
    'Spanish': 'es',
    'Swahili': 'sw',
    'Swedish': 'sv',
    'Thai': 'th',
    'Turkish': 'tr',
    'Ukrainian': 'uk',
    'Vietnamese': 'vi',
    'Welsh': 'cy',
    'Yiddish': 'yi',
}

class ServiceError(Exception):
    pass

def set_app_id(new_app_id):
	global app_id
	app_id = new_app_id

# While Google provides a way to retrieve languages,
# it includes unsupported languages in the response'
# We will just return known supported languages
# as defined here: 
# http://code.google.com/apis/language/translate/v2/using_rest.html#language-params
def get_languages():
    langs = list(LANGUAGES.values())
    langs.sort()
    return langs

"""
# Example of how to interrogate Google for languages
# but note warning above
def get_languages():
    args = {'key': app_id}
    url = '%s?%s' % (api_languages_url, urllib.parse.urlencode(args))
    try:
        sock = urllib.request.urlopen(url)
    except urllib.error.HTTPError:
        raise ServiceError('Error connecting to ' + url)
    content = sock.read()
    data = json.loads(str(content,encoding='utf-8'))
    return [lang['language'] for lang in data['data']['languages']]
"""

def _run_query(args):
    url = '%s?%s' % (api_translate_url, urllib.parse.urlencode(args))
    try:
        content = urllib.request.urlopen(url).read()
    except urllib.error.HTTPError:
        raise ServiceError('Error connecting to ' + url)
    result = json.loads(str(content,encoding='utf-8'))
    try:
        return result['data']['translations'][0]['translatedText']
    except KeyError:
        pass
    return None

def translate(phrase, source, target):
    if not app_id:
        raise ValueError("AppId needs to be set by set_app_id")
    args = {
        'key': app_id,
        'source': source,
        'target': target,
        'q': phrase,
    }
    return _run_query(args)

if __name__ == '__main__':
    set_app_id('AIzaSyAPc_-loqfyXALPxfSNtW0W6-QYglnI3Jg')
    langs = get_languages()
    print(type(langs),langs)
    for lang in ('fr','de','it','es'):
        print(lang)
        for phrase in ('Home','home','Search','search'):
            print('\tsrc:', phrase)
            print('\ttrg:', translate(phrase,'en',lang))
